package mapper;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.HttpServlet;
import server.Request;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Mapper {

    private MappedHost mappedHost;
    public HttpServlet findFirstServlet(Request request) {
        return mappedHost.findFirstServlet(request);
    }

    public Mapper() {
        this("server.xml");
    }

    public Mapper(String serverXmlPath) {
        //
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(serverXmlPath);
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//Server/Service/Engine/Host");
            if (selectNodes.size() > 0) {
                this.mappedHost = new MappedHost(selectNodes);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }


    // ---------------------

    private String webXmlPath;
    private String webXmlContext;



    public Map<String,HttpServlet> servletMap;

    public HttpServlet findServlet(Request request) {
        return servletMap.get(request.getUrl());

    }
}
